import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart'as http;
import '../../../config.dart';
import '../../abstract-loading-table.dart';
import '${util.dartName(table.javaName)}.dart';

class ${util.firstUpper(table.javaName)}TablePage extends LoadingTable<${util.firstUpper(table.javaName)}> {

  ${util.firstUpper(table.javaName)}TablePage({Key key, String name, String title}) : super(key : key, name: name, title: title);

  bool _loading = false;
  int _page = 1;

  @override
  Future<List<${util.firstUpper(table.javaName)}>> loadingData() {
     return _load();
  }

  @override
  List<SortDataColumn> sortDataColumns() {
    return <SortDataColumn>[
    <#if table.columnList??>
        <#list table.columnList as column>
        new SortDataColumn.sort(
            label: const Text('${util.comment(column)}'),
            <#if util.isNumber(column)>
            numeric: true,
            </#if>
        ),
        </#list>
    </#if>
    ];
  }

  @override
  List<Widget> celles(${util.firstUpper(table.javaName)} ${util.firstLower(table.javaName)}) {
    return <Widget>[
    <#if table.columnList??>
        <#list table.columnList as column>
     new Text('${r'${'}${util.firstLower(table.javaName)}.${column.property}}'),
        </#list>
    </#if>
    ];
  }

  Future<List<${util.firstUpper(table.javaName)}>> _load() async {
    if (_loading) {
      return null;
    }

    _loading = true;
    var url = "${SERER_URL}/adminUser/list/json?page$_page";
    print("url: $url");
    var httpClient = new HttpClient();
    httpClient.connectionTimeout = Duration(seconds: 3);

    try {
        var request = await httpClient.getUrl(Uri.parse(url));
        var response = await request.close();
        if (response.statusCode == HttpStatus.ok) {
            var responseData = await response.transform(utf8.decoder).join();
            var data = json.decode(responseData)['data']['beans'];
            _page += 1;
            List<AdminUser> list = new List();
            if (data is List) {
                data.forEach((dynamic e) {
                    ${util.firstUpper(table.javaName)} ${util.firstLower(table.javaName)} = new ${util.firstUpper(table.javaName)}(${util.dartJsonBeanParams(table, 'e')});
                    list.add(${util.firstLower(table.javaName)});
                });
            }
            return Future.value(list);
        } else {
            return Future.error("error!!!");
        }
    } catch (exception) {
        return Future.error("$exception");
    } finally {
        _loading = false;
    }
  }
}
